/**
 * 示例一
 */

// 1. 封装栈类(基于数组形式) 后进先出
function Stack() {
    this.items = []

    Stack.prototype.push = function (element) {
        this.items.push(element)
    }
    Stack.prototype.pop = function () {
        return this.items.pop()
    }
    Stack.prototype.peek = function () {
        return this.items[this.items.length - 1]
    }
    Stack.prototype.isEmpty = function () {
        return this.items.length == 0
    }
    Stack.prototype.size = function () {
        return this.items.length
    }
    Stack.prototype.toString = function () {
        var itemsToString = ''
        this.items.forEach(item => {
            itemsToString += item + ','
        });
        return itemsToString
    }
}

// 2. 栈的使用
var stack = new Stack()
stack.push(30)
stack.push(20)
stack.push(10)

console.log(stack.pop()) // 10
console.log(stack.peek()) // 20
console.log(stack.isEmpty()) // false
console.log(stack.size()) // 2
console.log(stack.toString())// 30 20

/**
 * 示例二
 */

function DecToBin(decNumber) {
    var s = new Stack()
    // 存
    while (decNumber > 0) {
        s.push(decNumber % 2)
        decNumber = Math.floor(decNumber / 2)
    }
    // 取
    var decString = ''
    while (!s.isEmpty()) {
        decString += s.pop()
    }
    return decString
}

console.log(DecToBin(10)) // 1010
console.log(DecToBin(100)) // 1100100
console.log(DecToBin(1000)) // 1111101000

